package com.dance.netty.bio;

import com.sun.istack.internal.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

    public static void main(String[] args) throws IOException {

        // 创建一个线程池
        // 参数 0 max 60 s syncQueue<Runnable>
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 创建服务器 绑定 6666 端口
        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器在6666端口开始监听......");

        while(true) {

            // 阻塞 等待客户端连接
            final Socket accept = serverSocket.accept();

            // 获取到一个客户端连接
            System.out.println(accept.getInetAddress().getHostAddress() + " 连接成功");

            // 创建一个线程与之通讯(单独写一个方法)
            executorService.execute(() -> {
                System.out.println("线程信息: { id: "+Thread.currentThread().getId() +", name: " +Thread.currentThread().getName() +" }");
                // 可以和客户端通讯
                handler(accept);
            });
        }
    }

    /**
     * 处理和客户端通讯
     */
    public static void handler(@NotNull final Socket socket){
        try {
            byte[] bytes = new byte[1024];
            // 获取输入流
            InputStream inputStream = socket.getInputStream();

            // 读取客户端数据
            while (true){
                int read = inputStream.read(bytes);
                if (read != -1){
                    System.out.println(new String(bytes,0,read));
                }else{
                    break;
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                System.out.println(socket.getInetAddress().getHostAddress() + " 连接关闭");
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
